package com.syedu.day14.homework;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 统计一段文章中每个单词出现的次数,并且按照出现次数降序排列,如果次数相同,则按照单词字母字典顺序排列
 (使用Map集合完成)
 */
public class Exercise {
    static Pattern pattern = Pattern.compile("[A-Za-z]+");

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        String str = "There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.\n" +
                "\n" +
                "　　May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.";
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            String word = matcher.group();
            if (map.containsKey(word)) {
                map.put(word, map.get(word) + 1);
            } else {
                map.put(word, 1);
            }
        }

        //自定义实体封装数据
        //遍历map
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        List<Map.Entry<String, Integer>> list = new ArrayList<>(entries);
        Collections.sort(list, (o1, o2) -> {
            int result = o2.getValue().compareTo(o1.getValue());
            if (result == 0) {
                result = o1.getKey().compareTo(o2.getKey());
            }
            return result;
        });

        list.forEach(System.out::println);
    }
}
